package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaAsset;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.domain.OaRegularFlow;
import com.dkm.orproject.dkmoa.service.OaAssetService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.Tools;
import io.swagger.annotations.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  @ClassName : OaAssetAction  //类名
 *  @Description : 资产  //描述
 *  @Author : 石智诚  //作者
 *  @Date: 2020-11-24 15:33  //时间
 */

@RestController
@RequestMapping("/OaAssetAction")
public class OaAssetAction {
    @Resource
    OaAssetService service;
    /**
     * 工具类
     */
    @Resource
    Tools tools;


    /**
     * 回调值
     */
    int row=0;

    /**
     * 日志
     */
    OaLog log;

    /**
     * 登陆人
     */
    OaPersonnel personnel;

    /**
     * 回调map
     */
    Map<String,Object> map;

    /**
     * 资产查看
     * @param asset 资产
     * @param limit 页面显示的行数
     * @param page  页数
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param request 请求
     * @return map
     */
    @UserLoginToken
    @GetMapping("assetFindAll")
    public Map<String,Object> assetFindAll(OaAsset asset, Integer limit, Integer page,
                                             String startDate, String endDate, HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)){
            tools.rowMap(map,0,log);
        }
        try {
            List<OaAsset> all = service.findAll(asset, page, limit, startDate, endDate);
            Long count = service.rowCount(asset, startDate, endDate);
            return   Tools.maps(all,count);
        } catch (Exception e) {
            addErrorLog(request,"资产查看",e);
        }
        return null;
    }
    /**
     * 根据id 查询
     * @param id 资产Id
     * @param request 请求
     * @return map
     */
    @ApiOperation(value = "资产查找id", notes = "资产查找id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "资产类型id",dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaRegularFlow.class),
    })

    @UserLoginToken
    @GetMapping("assetFindById/{id}")
    public OaAsset assetFindById(@PathVariable("id") Long id, HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)) {
            tools.rowMap(map,0,log);
        }
        try {
            return service.selectByPrimaryKey(id);

        } catch (Exception e) {
            addErrorLog(request,"资产根据id查找",e);
        }
        return  null;
    }

    /**
     * 根据资产id删除
     * @param id 资产id
     * @param request 请求
     * @return map
     */
    @ApiOperation(value = "资产id删除", notes = "资产id删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "资产Id",dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "删除成功"),
    })
    @UserLoginToken
    @DeleteMapping("assetDeleteById/{id}")
    public Map<String,Object> deleteById(@PathVariable("id") Long id,HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)) {
            tools.rowMap(map,0,log);
        }
        try {
            OaAsset asset = service.selectByPrimaryKey(id);
            row = service.deleteById(id);
            log.setLogTitle("删除模块");
            log.setLogBody(JSON.toJSON(asset).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"资产根据id删除",e);
        }
        return  map;
    }

    /**
     * 根据资产id批量删除
     * @param ids 资产id
     * @param request 请求
     * @return map
     */
    @ApiOperation(value = "资产批量删除", notes = "资产批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "资产Id",dataType = "Long[]",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "删除成功"),
    })
    @UserLoginToken
    @DeleteMapping("assetDeleteAll")
    public Map<String,Object> assetDeleteAl(@RequestParam("ids[]") Long[] ids,HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)) {
            tools.rowMap(map,0,log);
        }
        try {
            List<Long> list = Arrays.asList(ids);
            row=service.delteAll(list);
            log.setLogTitle("删除模块");
            log.setLogBody(JSON.toJSON(row).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"资产根据id删除",e);
        }
        return  map;
    }

    /**
     * 资产增加或者更新
     * @param asset 资产模型
     * @param request 请求
     * @return map
     */
    @UserLoginToken
    @PostMapping("assetAddOrUpdate")
    public Map<String, Object> addOrUpdate(OaAsset asset, HttpServletRequest request){
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)){
            tools.rowMap(map,0,log);
        }
        try {
            if (asset.getPkAssetId()!=null&& asset.getPkAssetId()>0){
                asset.setUpdatedBy(personnel.getPersonnelName());
                asset.setUpdatedTime(new Date());
                row = service.updateById(asset);
                log.setLogTitle("资产更新");
            }else {
                asset.setCreatedBy(personnel.getPersonnelName());
                asset.setCreatedTime(new Date());
                row=service.insert(asset);
                log.setLogTitle("资产增加");
            }
            log.setLogBody(JSON.toJSON(asset).toString());
            log.setIsRevision("1");
            tools.rowMap(map,row,log);
        } catch (Exception e) {
            addErrorLog(request,"资产增加或者更新",e);
        }
        return  map;
    }
    /**
     * 查询资产条码是否重复
     * @param asset 关键字或者人员ID
     * @param request 请求
     * @return 1和0
     */
    @UserLoginToken
    @GetMapping("selectCode")
    public Map<String,Object>findByAccount(OaAsset asset,HttpServletRequest request){
        try {
            row = service.codeCount(asset);
            tools.rowMap(map, row, log);
        }catch (Exception e){
            addErrorLog(request,"查询资产条码是否重复",e);
        }
        return map;
    }

    /**
     * 下拉框
     *
     * @param request 请求
     * @return
     */
    @UserLoginToken
    @GetMapping("selectAll")
    public Map<String, Object> selectAll(@RequestParam(value = "id", required = false) Long id, HttpServletRequest request) {
        rowMap(request);
        if (ObjectUtils.isEmpty(personnel)) {
            tools.rowMap(map, 0, log);
        }
        try {
            List<OaAsset> assets = service.selectAll(id);
            map.put("data", assets);
        } catch (Exception e) {
            addErrorLog(request, "下拉框查询", e);
        }
        return  map;
    }
    /**
     * 收集报错日志
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title 模块标题
     * @param e 异常参数
     */
    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        //后台打印报错信息
        e.printStackTrace();
        //获取当前操作人
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log=new OaLog();
        //日志类型
        log.setLogType("0");
        //日志内容
        log.setLogBody(e.getLocalizedMessage());
        //日志标题
        log.setLogTitle(title);
        //请求地址
        log.setLogIp(request.getRemoteAddr());
        //判断当前登陆人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            //当前操作人名称
            log.setCreatedBy(personnel.getPersonnelName());
        }
        //存入报错日志
        tools.errorMap(log);
    }
    /**
     * 优化代码 获取当前登陆人信息
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if(ObjectUtils.isEmpty(personnel)){
            return;
        }
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }

    /**
     * 日期格式化
     *
     * @param binder 服务器参数转换器
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}
